/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package DAO;

import DTO.Task;
import DTO.Tasks;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import util.DBUtil;

/**
 *
 * @author ThanhTai
 */
public class TaskDAO {

    public Tasks GetAllTask(String condition) throws SQLException, Exception {

        DBUtil util = new DBUtil();
        Connection conn = null;
        Statement stm = null;
        StringBuilder strBuilder = new StringBuilder();
        List<Task> taskList = new ArrayList<Task>();
        ResultSet rs = null;
        Task task;

        try {
            Class.forName(util.getDriverName());
            DriverManager.registerDriver(new com.microsoft.sqlserver.jdbc.SQLServerDriver());
            conn = DriverManager.getConnection(util.getURL(), util.getUsername(), util.getPassword());
            strBuilder.append("SELECT * FROM Tasks");
            if (condition != null && !condition.equals("")) {
                strBuilder.append(condition);
            }
            stm = conn.createStatement();
            rs = stm.executeQuery(strBuilder.toString());
            taskList = new ArrayList<Task>();
            while (rs.next()) {
                task = new Task(rs.getInt("TaskID"), rs.getString("TaskName"),rs.getInt("MinestoneID"),
                        rs.getString("username"), rs.getString("Description"), new DTO.Date(rs.getDate("StartDay")), new DTO.Date(rs.getDate("EndDay")), rs.getString("Status"));
                taskList.add(task);
            }
            return new Tasks(taskList);
        } catch (SQLException e) {
            throw (e);
        } catch (Exception e) {
            throw (e);
        } finally {
            try {
                rs.close();
            } catch (SQLException e) {
                throw (e);
            }
            try {
                stm.close();
            } catch (SQLException e) {
                throw (e);
            }
            try {
                conn.close();
            } catch (SQLException e) {
                throw (e);
            }
        }
    }
}
